<script setup>
import { reactive, ref, watch, nextTick } from "vue";
import summaryApi from "@/api/summaryApi.js";

import { use } from "echarts/core";
import { BarChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import VChart, { THEME_KEY } from "vue-echarts";

use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  BarChart,
  CanvasRenderer,
  GridComponent,
]);

const props = defineProps({
  searchParam: {
    type: Object,
    default() {
      return {
        planId: "",
        schoolId: ""
      }
    }
  },
  data: {
    type: Array,
    default: []
  }
});

const params = reactive({ showType: 1, sex: "", gradeId: "" })

const dataList = ref([]);

const loading = ref(false);
const scrollbar = ref(true);
const scroll = {
  x: 200,
  y: 600
};
let data = ref([]);
let gradeList = ref([]);
const headerStyle = {
  borderBottom: "none",
  fontSize: "18px",
};

const columns = reactive([
  { dataIndex: "dataKey", title: "班级", width: 100 },
  { dataIndex: "totalCount", title: "总人数", width: 80 },
  { dataIndex: "testCount", title: "实测人数", width: 90 },
  { dataIndex: "missExamCount", title: "缺考人数", width: 90 },
  { dataIndex: "freeTestCount", title: "免考人数", width: 90 },
  { slotName: "bestRate", title: "优秀率", width: 120 },
  { slotName: "wellRate", title: "良好率", width: 120 },
  { slotName: "passRate", title: "及格率", width: 120 },
  { slotName: "noPassRate", title: "不及格率", width: 120 },
  { slotName: "qualifiedRate", title: "合格率", width: 120 },
]);

const gradeBarOption = reactive({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
  },
  legend: {},
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  yAxis: {
    type: "value",
    name: "百分比（%）",
    min: 0,
    max: 100,
    boundaryGap: [0, 0.01],
    axisLabel: {
      show: true,
      interval: 0, // 使x轴文字显示全
      color: "#666666",
      formatter: "{value}%", //y轴数值，带百分号
    },
  },
  xAxis: {
    type: "category",
    data: [],
  },
  series: [],
});

let allClassData = [];
const querySummaryData = () => {
  loading.value = true;
  let queryParam = Object.assign({}, params);
  let searchParams = Object.assign({}, props.searchParam, queryParam);
  summaryApi.queryData(searchParams).then((res) => {
    buildClassesData(res.grade);
    loading.value = false;
  });
};

const buildClassesData = (classesData) => {
  let gradeItemList = [];
  allClassData = [];
  classesData.forEach(item => {
    gradeItemList.push({
      value: item.prjCode,
      label: item.dataKey
    });
    if (item.classesSummaryList && item.classesSummaryList.length > 0) {
      item.classesSummaryList.forEach(classes => {
        allClassData.push(classes);
      })
    }
  })
  gradeList.value = gradeItemList;
  if (gradeItemList.length > 0) {
    params.gradeId = gradeItemList[0].value;
    filterClassesData(gradeItemList[0].value);
  }
}

const filterClassesData = async (gradeId) => {
  // 先清空当前数据
  dataList.value = [];
  gradeBarOption.xAxis.data = [];
  gradeBarOption.series = [];

  // 从全部数据中过滤出当前年级的班级数据
  let filterData = allClassData.filter(item => item.parentId == gradeId.toString());
  
  // 按班级名称排序
  filterData.sort((a, b) => {
    return a.dataKey.localeCompare(b.dataKey);
  });

  // 更新数据和图表
  dataList.value = filterData;
  buildGradeBarOption(filterData);

  // 等待下一个渲染周期
  await nextTick();
}

const buildGradeBarOption = (gradeData) => {
  let xAxisData = [];
  let series = [];
  let categories = ["优秀率", "良好率", "及格率", "不及格率"];
  categories.forEach((category) => {
    series.push({
      name: category,
      type: "bar",
      data: [],
    });
  });
  gradeData.forEach((item) => {
    xAxisData.push(item.dataKey);
    series.forEach((serie) => {
      if (serie.name == "优秀率") {
        serie.data.push(item.bestRate);
      } else if (serie.name == "良好率") {
        serie.data.push(item.wellRate);
      } else if (serie.name == "及格率") {
        serie.data.push(item.passRate);
      } else if (serie.name == "不及格率") {
        serie.data.push(item.noPassRate);
      }
    });
  });
  gradeBarOption.xAxis.data = xAxisData;
  gradeBarOption.series = series;
};

const chartRef = ref(null);

// 暴露方法给父组件
defineExpose({
  getChart() {
    return chartRef.value;
  },
  setShowType(type) {
    params.showType = type;
  },
  getParams() {
    return params;
  },
  async filterClassesData(gradeId) {
    // 先清空当前数据
    dataList.value = [];
    gradeBarOption.xAxis.data = [];
    gradeBarOption.series = [];

    // 从全部数据中过滤出当前年级的班级数据
    let filterData = allClassData.filter(item => item.parentId == gradeId.toString());
    
    // 按班级名称排序
    filterData.sort((a, b) => {
      return a.dataKey.localeCompare(b.dataKey);
    });

    // 更新数据和图表
    dataList.value = filterData;
    buildGradeBarOption(filterData);

    // 等待下一个渲染周期
    await nextTick();
  }
});

watch(
  () => props.data,
  (newVal, oldVal) => {
    let datas = !newVal ? [] : newVal;
    buildClassesData(datas);
  }, { deep: true, immediate: true }
)

</script>
<template>
  <a-card title="按班级统计" style="margin-top: 16px" :header-style="headerStyle">
    <template #extra>
      <a-space>
        <a-radio-group v-model="params.showType" type="button">
          <a-radio :value="1"><icon-list /></a-radio>
          <a-radio :value="2"><icon-bar-chart /></a-radio>
        </a-radio-group>
        <span>年级</span>
        <a-select style="width: 120px;" @change="filterClassesData" v-model="params.gradeId" placeholder="请选择">
          <a-option v-for="item in gradeList" :key="item.value" :value="item.value" :label="item.label"></a-option>
        </a-select>
        <a-radio-group type="button" v-model="params.sex" @change="querySummaryData">
          <a-radio value="">全部</a-radio>
          <a-radio value="1">男</a-radio>
          <a-radio value="2">女</a-radio>
        </a-radio-group>
      </a-space>
    </template>
    <div v-if="params.showType == 2" style="border: 1px solid #e5e6e5; padding: 16px">
      <v-chart ref="chartRef" :option="gradeBarOption" autoresize class="basechart" />
    </div>
    <a-table row-key="dataKey" :scroll="scroll" :scrollbar="scrollbar" v-else :data="dataList" :columns="columns"
      :loading="loading" :pagination="false">
      <template #bestRate="{ record }">
        <a-progress status="success" size="mini" :percent="record.bestRate / 100" />
        {{ record.bestRate + "%" }}
      </template>
      <template #wellRate="{ record }">
        <a-progress status="primary" size="mini" :percent="record.wellRate / 100" />
        {{ record.wellRate + "%" }}
      </template>
      <template #passRate="{ record }">
        <a-progress status="warning" size="mini" :percent="record.passRate / 100" />
        {{ record.passRate + "%" }}
      </template>
      <template #noPassRate="{ record }">
        <a-progress status="warning" size="mini" :percent="record.noPassRate / 100" />
        {{ record.noPassRate + "%" }}
      </template>
      <template #qualifiedRate="{ record }">
        <a-progress status="primary" size="mini" :percent="record.qualifiedRate / 100" />
        {{ record.qualifiedRate + "%" }}
      </template>
    </a-table>
  </a-card>
</template>